package com.webserver_v5.core;

import com.webserver_v5.http.HttpServletRequest;
import com.webserver_v5.http.HttpServletResponse;

import java.io.File;
import java.net.URISyntaxException;

public class DispatcherServlet {
    private static DispatcherServlet instance = new DispatcherServlet();

    private static File rootDir;
    private static File staticDir;

    private DispatcherServlet(){}

    public static DispatcherServlet getInstance(){
        return instance;
    }
    static {
        try {
            rootDir = new File(
                    ClientHandler.class.getClassLoader()
                            .getResource(".").toURI()
            );
            staticDir = new File(rootDir,"static");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }
    public void service(HttpServletRequest request, HttpServletResponse response){
        String path = request.getUri();
        File file = new File(staticDir,path);
        if (file.isFile()){
            response.setContentFile(file);

            response.addHeader("Server","BirdWebServer");
        }else {
            response.setStatusCode(404) ;
            response.setStatusReason("NotFound");
            file = new File(staticDir,"root/404.html");
            response.setContentFile(file);

        }
    }

}
